package p3.cse;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * This activity adds new accounts to the account list for encryption.
 * 
 * @see Unlocked
 * @see /res/layout/add.xml
 */
public final class Add extends Activity {
	/**
	 * The "ok" button listener triggered onClick for add.xml form. There is no
	 * checking quality of password.
	 */
	private OnClickListener ok = new OnClickListener() {
		public void onClick(final View v) {
			String account, url, username, password;
			Filer filer = Filer.getInstance();

			EditText acc = (EditText) findViewById(R.id.account_edittext);
			account = acc.getText().toString();

			// verify the account doesn't already exist
			if (filer.checkAccountExists(account)) {
				TextView warning = (TextView) findViewById(R.id.Warning);
				warning.setText("Duplicate Account Name.");
				warning.setVisibility(View.VISIBLE);
				return;
			}

			EditText urledit = (EditText) findViewById(R.id.url_edittext);
			url = urledit.getText().toString();

			EditText user = (EditText) findViewById(R.id.username_edittext);
			username = user.getText().toString();

			EditText pass = (EditText) findViewById(R.id.password_edittext);
			password = pass.getText().toString();

			Entry entry = new Entry(account, url, username, password);

			boolean addedsuccess = filer.addEntry(entry);
			try {
				if (addedsuccess) {
					filer.writeFile();
				} else {
					Log.d("adding entry", "adding entry failed.");
				}
			} catch (IOException e) {
				Log.e("Write Error",
						"IO Error on file writing of database file.", e);
			}
			// Intent mainunlocked = new Intent(Add.this, mainunlocked.class);
			// startActivity(mainunlocked);
			finish();
		}
	};

	/**
	 * Android constructor for the Add activity. Loads the add.xml layout and
	 * binds "Ok" button to ok button event.
	 * 
	 * {@inheritDoc}
	 * 
	 * @see /res/layout/add.xml
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add);
		Button okBtn = (Button) this.findViewById(R.id.add_ok_button);
		okBtn.setOnClickListener(ok);
	}
}
